//
//  ElectricityViewController.m
//  EasyToo
//
//  Created by linshengqin on 13-8-24.
//
//

#import "ElectricityViewController.h"
#import "ElectricityDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ElectricityViewController ()

@end

@implementation ElectricityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)initMainView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight])];
    [self.view addSubview:_bgScrollView];
    _bgScrollView.contentSize = CGSizeMake(320, 1000);
    _bgScrollView.showsVerticalScrollIndicator = YES;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
     [self.view setBackgroundColor:BackgroundColor];

	// Do any additional setup after loading the view.
    eletricity_model = [ElectricityModel sharedata];
    
    [self.navigationItem setTitle:@"电费"];
    [self initMainView];
    [self initDetailView];
}

-(void)initDetailView
{
    UIImage *image = [UIImage imageNamed:@"shurubi"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ;
    imageView.frame = CGRectMake(20, 20, 10, 15);
    [_bgScrollView addSubview:imageView];
    
    UILabel *label_user = [[[UILabel alloc]initWithFrame:CGRectMake(30, 10, 180, 30)]autorelease];
    label_user.text = @"填写用户信息:";
    [label_user setBackgroundColor:[UIColor clearColor]];
    
    [_bgScrollView addSubview:label_user];
    
    self.account = [[[UITextField alloc] initWithFrame:CGRectMake(30, 40, 250, 30)]autorelease];
    [self.account setBorderStyle:UITextBorderStyleBezel];
    _account.layer.borderColor = [UIColor grayColor].CGColor;
    _account.layer.borderWidth = 1 ;
    _account.layer.cornerRadius = 10 ;
    self.account.placeholder = @"户号 :";
    self.account.borderStyle = UITextBorderStyleRoundedRect;
    self.account.delegate = self;
    self.account.returnKeyType = UIReturnKeyDone;
    _account.tag = 300;
    [_bgScrollView addSubview:self.account];
    
    UILabel *label_tip = [[[UILabel alloc]initWithFrame:CGRectMake(30,70, 180, 20)]autorelease];
    label_tip.text = @"目前仅支持广州地区用户";
    label_tip.font = [UIFont systemFontOfSize:10];
    [label_tip setBackgroundColor:[UIColor clearColor]];
    
    [_bgScrollView addSubview:label_tip];
    
    
    UIImageView *imageView2 = [[UIImageView alloc] initWithImage:image] ;
    imageView2.frame = CGRectMake(20, 110, 10, 15);
    [_bgScrollView addSubview:imageView2];
    
    UILabel *label_value = [[[UILabel alloc]initWithFrame:CGRectMake(30, 100, 180, 30)]autorelease];
    label_value.text = @"选择月份:";
    [label_value setBackgroundColor:[UIColor clearColor]];
    
    [_bgScrollView addSubview:label_value];
    
    self.text_value = [[[UITextField alloc] initWithFrame:CGRectMake(30, 130, 250, 30)]autorelease];
    [self.text_value setBorderStyle:UITextBorderStyleBezel];
    self.text_value.borderStyle = UITextBorderStyleRoundedRect;
    _text_value.layer.borderColor = [UIColor grayColor].CGColor;
    _text_value.layer.borderWidth = 1 ;
    _text_value.layer.cornerRadius = 10 ;
    self.text_value.returnKeyType =UIReturnKeyDone;
    [self.text_value setDelegate:self];
    
    [_bgScrollView addSubview:self.text_value];
    // 建立 UIToolbar
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelPicker)];
    // 把按鈕加進 UIToolbar
    toolBar.items = [NSArray arrayWithObject:right];
    self.text_value.inputAccessoryView = toolBar;
    
    pickerArray = [[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"全部月份",  nil] retain];
    selectPicker = [[[UIPickerView alloc]initWithFrame:CGRectZero]autorelease];
    selectPicker.showsSelectionIndicator = YES;
    selectPicker.frame = CGRectMake(0, 100, 0, 0);
    
    self.text_value.inputAccessoryView = toolBar;
    self.text_value.delegate = self;
    selectPicker.delegate = self;
    selectPicker.dataSource = self;
    selectPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    self.text_value.inputView = selectPicker;
    
    
    UIButton *nextStep =[UIButton buttonWithType:UIButtonTypeCustom];
    nextStep.frame = CGRectMake(30, 190, 260, 40);
    [nextStep setTitle:@"下一步" forState:UIControlStateNormal];        //设置button在没有选中的时候显示的字体
   
    nextStep.layer.cornerRadius =10 ;

    nextStep.titleLabel.font = [UIFont systemFontOfSize:14.0f];         //设置button显示字体的大小
    [nextStep setBackgroundImage:[UIImage imageNamed:@"button_3"] forState:UIControlStateNormal];
    
    [nextStep addTarget:self action:@selector(confirmMessge:) forControlEvents:UIControlEventTouchUpInside];
    
    [_bgScrollView addSubview:nextStep];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return  YES ;
}


#pragma picker delegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [pickerArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [pickerArray objectAtIndex:row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[[UILabel alloc] init]autorelease];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        //        pickerLabel.minimumFontSize =100.;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if( textField.tag == 300)
    {
        if( ![self validateAccount:textField.text] )
        {
            UIAlertView *_baseAlert = [[[UIAlertView alloc]  initWithTitle:@"提示" message:@"请输入正确的电费帐号"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil]autorelease];
            [_baseAlert show];
        }
    }
    else
    {
        NSInteger row = [selectPicker selectedRowInComponent:0];
        self.text_value.text = [pickerArray objectAtIndex:row];
    }
}


// 按下完成鈕後的 method
-(void) cancelPicker {
    [self.text_value endEditing:YES];
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	return 100.0;
}

-(void)confirmMessge:(id)sender
{
    if ([_account.text isEqualToString:@""] == YES || [_text_value.text isEqualToString:@""] == YES || _account.text == nil || _text_value.text == nil)
    {
        UIAlertView *_baseAlert = [[[UIAlertView alloc]  initWithTitle:@"出错" message:@"用户名信息不能为空"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil]autorelease];
        [_baseAlert show];
    }
    else if(![self validateAccount:_account.text])
    {
        UIAlertView *_baseAlert = [[[UIAlertView alloc]  initWithTitle:@"出错" message:@"请输入正确的电费帐号"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil]autorelease];
        [_baseAlert show];
        _account.text = @"";
    }
    else
    {
        [self checkElectricInfo];
        baseAlert = [[[UIAlertView alloc] initWithTitle:@"Please Wait" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
        [baseAlert show];
        // Create and add the activity indicator
        aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        aiv.center = CGPointMake(baseAlert.bounds.size.width / 2.0f, baseAlert.bounds.size.height - 40.0f);
        [aiv startAnimating];
        [baseAlert addSubview:aiv];
        [aiv release];
    }
}

-(void)checkElectricInfo
{
    eletricity_model =[ElectricityModel sharedata];
    [ElectricityManager shareManager].delegate = self;
    [[ElectricityManager shareManager] checkElectricInfo:self.account.text];    
}

- (void)onCheckElectricInfoFinish:(BOOL)isSuccess
             electricFeeInfoArray:(NSMutableArray*)electricFeeInfoArray
{
    if(isSuccess)
    {
        eletricity_model.electricFeeInfoArray = electricFeeInfoArray;
        printf("count is:%d\n",[eletricity_model.electricFeeInfoArray count]);
        [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
        
        if( [eletricity_model.electricFeeInfoArray count] > 0)
        {
            ElectricityDetailViewController *detail = [[[ElectricityDetailViewController alloc]init]autorelease];
            [eletricity_model.account setString:_account.text];
            [eletricity_model.month setString:_text_value.text];
            [self.navigationController pushViewController:detail animated:YES];
        }
        else
        {
            baseAlert = nil;
            baseAlert = [[[UIAlertView alloc] initWithTitle:@"查询无欠费数据" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil] autorelease];
            [baseAlert show];

        }
        //[selectPicker reloadAllComponents];
    }
    else
    {
        [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
        baseAlert = nil;
        baseAlert = [[[UIAlertView alloc] initWithTitle:@"查询的用户不存在" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
        [baseAlert show];
        
    }
}

- (void)dealloc
{
    [ElectricityManager shareManager].delegate = nil;
    [super dealloc];
}

//电费帐号
- (BOOL) validateAccount: (NSString *)account
{
    BOOL flag;
    if (account.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d+\\.\\d+)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:account];
}


@end
